<template>
  <el-card class="box-card">
    <MainGoBack name="溯源列表"></MainGoBack>
    <div class="supplier-detail">
      <div class="supplier-detail-item">
        <p class="sdi-title">
          <span></span>
          <em>基本信息</em>
        </p>
        <el-row>
          <el-col :span="6" v-for="item in basicInfo" :key="item.label">
            <span style="flex-shrink: 0">{{ item.label }}：</span>
            <span style="word-break: break-word">{{ orderInfo[item.key] }}</span>
          </el-col>
        </el-row>
      </div>
      <div class="supplier-detail-item">
        <p class="sdi-title">
          <span></span>
          <em>供应商信息</em>
        </p>
        <div class="main_table" style="min-height: 590px">
          <!-- 一级表头 -->
          <el-table
            ref="detailTable"
            v-loading="listLoading"
            :data="Twolist"
            element-loading-text="列表加载中"
            fit
            border
            highlight-current-row
            @expand-change="handleTwoChange"
            :expand-row-keys="expands"
            :row-key="getRowKeys"
          >
            <el-table-column type="expand">
              <!-- 这里定义展开行的内容 -->
              <template slot-scope="scope">
                <div
                  v-loading="threelistLoading"
                  element-loading-text="溯源信息加载中"
                >
                  <div class="box">
                    <div class="item flex-column">
                      <span class="item-title14">查询信息</span>
                      <span class="item-title12"
                        >溯源编码: {{ scope.row.infoFrom.trace_code }}</span
                      >
                      <span class="item-title12"
                        >当前查询次数: {{ scope.row.infoFrom.query_count }} 次</span
                      >
                      <span class="item-title12"
                        >首次查询时间: {{ scope.row.infoFrom.first_query_time }}</span
                      >
                    </div>
                    <div class="item flex-column">
                      <span class="item-title14">订单信息</span>
                      <span class="item-title12"
                        >下单客户: {{ scope.row.infoFrom.nickname }}</span
                      >
                      <span class="item-title12"
                        >下单数量: {{ scope.row.infoFrom.order_num }}</span
                      >
                      <span class="item-title12"
                        >发货数量: {{ scope.row.infoFrom.collected_num }}</span
                      >
                      <span class="item-title12"
                        >归属单号: {{ scope.row.infoFrom.order_sn }}</span
                      >
                      <span class="item-title12"
                        >退货数量: {{ scope.row.infoFrom.return_num }}</span
                      >
                    </div>
                    <div class="item flex-column">
                      <span class="item-title14">供应商信息</span>
                      <span class="item-title12"
                        >供应商资质:
                        <span
                          class="item-title14-images"
                          @click="openFiles(scope.row.infoFrom.company_qualification)"
                          >查看资质</span
                        ></span
                      >
                      <span class="item-title12"
                        >供应商名称: {{ scope.row.infoFrom.company_name }}</span
                      >
                      <span class="item-title12"
                        >联系地址: {{ scope.row.infoFrom.company_address }}</span
                      >
                    </div>
                    <div class="item flex-column">
                      <span class="item-title14">检测信息</span>
                      <!-- <span class="item-title12"
                        >检测报告图片:
                        <span class="item-title14-images"
                        @click="viewreport(scope.row.infoFrom.company_qualification)"
                          >查看报告</span
                        ></span
                      > -->
                      <span class="item-title12"
                        >检测项目: {{ scope.row.infoFrom.project.name }}
                      </span>
                      <span class="item-title12"
                        >检测人: {{ scope.row.infoFrom.testing_user }}</span
                      >
                      <span class="item-title12"
                        >检测结果:
                        <span v-if="scope.row.infoFrom.result == 1">合格</span>
                        <span v-if="scope.row.infoFrom.result == 2">不合格</span>
                      </span>
                      <span class="item-title12"
                        >抑制率 : {{ scope.row.infoFrom.inhibition_rate }}<span v-if="scope.row.infoFrom.inhibition_rate">%</span></span
                      >
                      <span class="item-title12"
                        >检测日期：{{ scope.row.infoFrom.time }}</span
                      >
                    </div>
                    <div
                      class="item flex-column"
                      v-if="scope.row.infoFrom.son_company"
                    >
                      <span class="item-title14">二级供应商信息</span>
                      <span class="item-title12"
                        >供应商名称:{{ scope.row.infoFrom.son_company.name }}
                        <!-- <span class="item-title14-images"
                          >查看资质</span> -->
                      </span>
                      <span class="item-title12"
                        >手机号: {{ scope.row.infoFrom.son_company.mobile }}</span
                      >
                      <span class="item-title12"
                        >营业执照:
                        <span
                          class="item-title14-images"
                          @click="openFi(scope.row.infoFrom.son_company.pics)"
                          >查看资质</span
                        >
                      </span>
                    </div>
                    <!-- <div class="item flex-column" v-else>
                      <span class="item-title14">...</span>
                    </div> -->
                  </div>
                  <div class="line"></div>
                  <div class="liucheng flex-btw">
                    <div class="liucheng-left">
                      <span class="liucheng-left-titles">溯源信息</span>
                      <el-steps
                        :active="scope.row.infoFrom.flowList.length"
                        align-center
                      >
                        <el-step
                          v-for="(item, index) in scope.row.infoFrom.flowList"
                          :key="index"
                        >
                          <template slot="title">
                            <span>{{ item.status_name }}</span>
                          </template>
                          <template slot="description">
                            <p
                              >{{ item.status_name }}:
                              {{ item.name }}</p
                            >
                            <p
                              >{{ item.status_name }}时间:
                              {{ item.time | timer }}</p
                            >
                          </template>
                        </el-step>
                      </el-steps>
                    </div>
                    <div class="liucheng-right">
                      <span
                        class="liucheng-right-titles"
                        style="margin-botton: 15px"
                        >留样视频</span
                      >
                      <div class="video" :id="scope.row.infoFrom.trace_code"></div>
                      <!-- <source src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4"
                          type="video/webm" /> -->
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商户" align="left" prop="name" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.order.nickname }}</span>
              </template>
            </el-table-column>
            <el-table-column label="电话" prop="order.mobile"> </el-table-column>
            <el-table-column label="配送数量" prop="sort_num">
            </el-table-column>
            <el-table-column label="溯源码" prop="delivery_zl">
              <template slot-scope="scope">
                <el-image :src="scope.row.qrcode_url" style="width: 60px" :preview-src-list="[scope.row.qrcode_url]"></el-image>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog title="供应商资质" :visible.sync="dialogVisibles" width="40%">
      <div
        class="dialog-zizhi"
        v-html="`${infoFrom.company_qualification}`"
      ></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibles = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibles = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
import { getSuyuanTwoList } from "@/api/traceability/index";
import { getTraceDetail, getTrace } from "@/api/traceability/index2";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dayjs from "dayjs"
import EZUIKit from "ezuikit-js";
import { detailData } from '../MockData'
const { basicInfo } = detailData
export default {
  data() {
    return {
      basicInfo,
      detailName: '',
      detailCreated_at: '',
      orderInfo: {},
      tableData: [],
      Twolist: [],
      listLoading: false,
      trace_code: "",
      expands: [],
      infoFrom: {
        // 溯源编码
        trace_code: null,
        // 查询次数
        query_count: null,
        // 查询时间
        first_query_time: null,
        // 下单客户
        nickname: null,
        // 下单数量
        order_num: null,
        // 发货数量
        collected_num: null,
        // 归属单号
        order_sn: null,
        // 退货数量
        return_num: null,
        // 供应商名称
        company_name: null,
        // 联系地址
        company_address: null,
        // 供应商资质
        company_qualification: null,
        // 流程
        flowList: [],
        // 供应商
        gongyingshangList: [],
        // 供应链
        gongyinglianList: [],
        // 药残检测信息
        inhibition_rate: null, //抑制率 如80.00%
        testing_user: null, //检测人
        result: null, //1 合格 2不合格
        time: null, //检测时间
        project: [], //检测项目  name名称
        son_company: null, //二级供应商参数
      },
      dialogVisibles: false,
      threelistLoading: false
    }
  },
  activated() {
    this.detailName = this.$route.query.name
    this.detailCreated_at = this.$route.query.created_at
    this.getDetail()
  },
  deactivated() {
    this.Twolist.map(el => {
      this.$refs.detailTable.toggleRowExpansion(el, false)
    })
  },
  methods: {
    getRowKeys(row) {
      return row.id;
    },
    getDetail() {
      this.listLoading = true
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          name: this.detailName,
          created_at: this.detailCreated_at
        }
      );
      getSuyuanTwoList(query).then(res => {
        if(res.errcode == 0) {
          this.orderInfo = res.data.order
          this.Twolist = res.data.list.map(el => {
            el.infoFrom = {
              // 溯源编码
              trace_code: null,
              // 查询次数
              query_count: null,
              // 查询时间
              first_query_time: null,
              // 下单客户
              nickname: null,
              // 下单数量
              order_num: null,
              // 发货数量
              collected_num: null,
              // 归属单号
              order_sn: null,
              // 退货数量
              return_num: null,
              // 供应商名称
              company_name: null,
              // 联系地址
              company_address: null,
              // 供应商资质
              company_qualification: null,
              // 流程
              flowList: [],
              // 供应商
              gongyingshangList: [],
              // 供应链
              gongyinglianList: [],
              // 药残检测信息
              inhibition_rate: null, //抑制率 如80.00%
              testing_user: null, //检测人
              result: null, //1 合格 2不合格
              time: null, //检测时间
              project: [], //检测项目  name名称
              son_company: null, //二级供应商参数
            }
            return el
          })
          this.listLoading = false
        }
      })
    },
    async handleSelectionChange(row, expanded) {
      let that = this;
      if (that.trace_code) {
        that.trace_code.stop();
      }
      this.tableData = [];
      this.TwolistLoading = true;

      // 创建一个新的数组来存储要展开的行的唯一标识
      const newExpanded = [];
      expanded.forEach((item) => {
        if (item.id === row.id) {
          newExpanded.push(item.id);
        }
      });
      this.expands = newExpanded;

      let data = {
        // created_at: '2024-10-22',
        created_at: this.detailCreated_at,
        name: row.name,
      };
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      await getSuyuanTwoList(query).then((res) => {
        if (res.errcode == 0) {
          that.$nextTick(function () {
            that.tableData = res.data.list;
            that.TwolistLoading = false;
            that.$forceUpdate();
          });
        } else {
          that.$message.error(res.errmsg);
        }
      });
    },
    async handleTwoChange(row, expanded) {
      let that = this;
      if(expanded.length) {
        const nameList = expanded.map(el => el.order.id)
        //  判断是展开就请求接口
        if(nameList.includes(row.order.id)) {
          this.threelistLoading = true
          // 获取溯源详情
          let getTraceDetail = this.getTraceDetail(row.id);
          // 获取流程
          let getFlow = this.getFlow(row.id);
          await Promise.all([getTraceDetail, getFlow]).then((res) => {
            let {
              order_trace,
              order_info,
              company_info,
              DrugResidueTesting,
              son_company,
            } = res[0];
            // 溯源编码
            row.infoFrom.trace_code = order_trace.trace_code || null;
            // 查询次数
            row.infoFrom.query_count = order_trace.query_count || null;
            // 查询时间
            row.infoFrom.first_query_time = order_trace.first_query_time || null;
            // 下单客户
            row.infoFrom.nickname = order_info.nickname || null;
            // 下单数量
            row.infoFrom.order_num = order_info.order_num || null;
            // 发货数量
            row.infoFrom.collected_num = order_info.collected_num || null;
            // 归属单号
            row.infoFrom.order_sn = order_info.order_sn || null;
            // 退货数量
            row.infoFrom.return_num = order_info.return_num || null;
            // 供应商名称
            row.infoFrom.company_name = company_info.company_name || null;
            // 联系地址
            row.infoFrom.company_address = company_info.company_address || null;
            // 供应商资质
            row.infoFrom.company_qualification =
              company_info.company_qualification || null;
              // console.log(res);
            row.infoFrom.flowList = res[1].list.reverse();
            console.log("row.infoFrom", row.infoFrom);
            //  药残检测信息
            if(DrugResidueTesting) {
              row.infoFrom.inhibition_rate =
                DrugResidueTesting.inhibition_rate || null; //抑制率
              row.infoFrom.testing_user = DrugResidueTesting.testing_user || null; //检测人
              row.infoFrom.result = DrugResidueTesting.result || null; //1 合格 2不合格
              row.infoFrom.time =
                this.getData(Number(DrugResidueTesting.time) * 1000) || null; //检测时间
              row.infoFrom.project = DrugResidueTesting.project || null; //检测项目 .name名字
            }
            //  二级供应商 如有 此参数有值 为name 姓名', 'contact', 'mobile' 手机号, 'pics 营业执照
            row.infoFrom.son_company = son_company;
            this.threelistLoading = false
            that.$nextTick(() => {
              // that.trace_code = that.infoFrom.trace_code
              if (company_info.company_yingshi) {
                console.log(row.infoFrom.trace_code);
                
                that.trace_code = new EZUIKit.EZUIKitPlayer({
                  id: row.infoFrom.trace_code, // 视频容器ID
                  accessToken: company_info.token,
                  url: company_info.company_yingshi,
                  width: 300,
                  height: 200,
                  audio: 0,
                  header: ["capturePicture"],
                  footer: ["broadcast", "hd", "fullScreen"],
                  handelError: (data) => {
                    that.trace_code.resume();
                    console.log("失败回调", data);
                    console.log(trace_code);
                  },
                });
                // console.log(that.player);
                // console.log('播放器已加载完成');
                that.trace_code.stop();
                that.trace_code.play();
              }
            });
            // )
    
            // 等待播放器加载完成后再调用 stop 和 play
    
            // loading.close();
          });
        }
      }
    },
    // 转换时间戳函数
    getData(n) {
      if (n) {
        let now = new Date(n);
        let y = now.getFullYear();
        let m = now.getMonth() + 1;
        let d = now.getDate();
        return (
          y +
          "-" +
          (m < 10 ? "0" + m : m) +
          "-" +
          (d < 10 ? "0" + d : d) +
          " " +
          now.toTimeString().substr(0, 8)
        );
      }
    },
    // 打开资质文件等图片
    openFiles(file) {
      if (file) {
        this.dialogVisibles = true;
        console.log("11111111111", this.infoFrom.company_qualification);
      } else {
        this.$message.error("文件不存在");
      }
    },
    // 获取溯源详情
    getTraceDetail(id) {
      return new Promise((resolve, reject) => {
        let data = {
          id,
        };
        let query = this.getPackage(data);

        getTrace(query).then((res) => {
          // console.log("res获取溯源详情", res);
          if (res.errcode == 0) {
            resolve(res.data);
          } else {
            reject(res.errmsg);
          }
        });
      });
    },
    // 获取流程
    getFlow(id) {
      return new Promise((resolve, reject) => {
        let data = {
          order_list_id: id,
        };
        let query = this.getPackage(data);
        getTraceDetail(query).then((res) => {
          // console.log("res获取流程", res);
          if (res.errcode == 0) {
            res.data.list = res.data.list.map(el => {
              el.time = dayjs(+el.time * 1000).format('YYYY-MM-DD HH:mm:ss')
              return el
            })
            resolve(res.data);
          } else {
            reject(res.errmsg);
          }
        });
      });
    },
    // 封装请求前函数
    getPackage(data) {
      return Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, data)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
    },
  }
}
</script>
<style lang="scss" scoped>
  @import './index.scss';
</style>